// pages/avatar/avatar.js
const { AvatarConfig, AVATAR_OPTIONS, DEFAULT_AVATAR_CONFIG } = require('../../utils/avatar-models.js')
const { avatarUtils } = require('../../utils/avatar-utils.js')
const { post } = require('../../utils/api.js')
const { showError, showSuccess, showToast } = require('../../utils/util.js')
const { navigateTo } = require('../../utils/router.js')

Page({
  data: {
    // Current avatar configuration
    currentAvatarConfig: {},
    originalAvatarConfig: {},
    
    // Edit mode state
    isEditing: false,
    
    // Loading states
    loading: false,
    saving: false,
    loadingText: 'Loading...',
    
    // Gender filter for hairstyles
    genderFilter: 'all',
    
    // Option data arrays
    faceShapeOptions: [],
    hairstyleOptions: [],
    filteredHairstyles: [],
    hairColorOptions: [],
    eyeShapeOptions: [],
    
    // Clothing options
    clothingCategories: [],
    currentClothingItems: [],
    currentClothingColors: [],
    
    // Accessory options
    glassesOptions: [],
    hatOptions: [],
    jewelryOptions: [],
    scarfOptions: []
  },

  onLoad(options) {
    // Check if editing existing avatar
    const isEditing = options.edit === 'true'
    
    this.setData({
      isEditing,
      loadingText: isEditing ? 'Loading avatar...' : 'Initializing editor...'
    })
    
    this.initializeEditor()
  },

  /**
   * Initialize avatar editor
   */
  async initializeEditor() {
    this.setData({ loading: true })
    
    try {
      // Initialize option data
      this.initializeOptions()
      
      // Load avatar configuration
      await this.loadAvatarConfig()
      
      // Update dependent data
      this.updateDependentData()
      
    } catch (error) {
      console.error('Failed to initialize avatar editor:', error)
      showError('Initialization failed, please try again')
    } finally {
      this.setData({ loading: false })
    }
  },

  /**
   * Initialize all option arrays
   */
  initializeOptions() {
    // Face shape options
    const faceShapeOptions = AVATAR_OPTIONS.FACE_SHAPES
    
    // Hairstyle options
    const hairstyleOptions = AVATAR_OPTIONS.HAIRSTYLES
    
    // Hair color options
    const hairColorOptions = AVATAR_OPTIONS.HAIR_COLORS
    
    // Eye shape options
    const eyeShapeOptions = AVATAR_OPTIONS.EYE_SHAPES
    
    // Clothing categories
    const clothingCategories = Object.keys(AVATAR_OPTIONS.CLOTHING).map(key => ({
      id: key.toLowerCase(),
      name: this.getClothingCategoryName(key)
    }))
    
    // Accessory options
    const glassesOptions = AVATAR_OPTIONS.ACCESSORIES.find(acc => acc.id === 'glasses').types
    const hatOptions = AVATAR_OPTIONS.ACCESSORIES.find(acc => acc.id === 'hat').types
    const jewelryOptions = AVATAR_OPTIONS.ACCESSORIES.find(acc => acc.id === 'jewelry').types
    const scarfOptions = AVATAR_OPTIONS.ACCESSORIES.find(acc => acc.id === 'scarf').types
    
    this.setData({
      faceShapeOptions,
      hairstyleOptions,
      filteredHairstyles: hairstyleOptions,
      hairColorOptions,
      eyeShapeOptions,
      clothingCategories,
      glassesOptions,
      hatOptions,
      jewelryOptions,
      scarfOptions
    })
  },

  /**
   * Get clothing category Chinese name
   */
  getClothingCategoryName(category) {
    const categoryNames = {
      'CASUAL': '休闲',
      'FORMAL': '正装',
      'DRESS': '连衣裙'
    }
    return categoryNames[category] || category
  },

  /**
   * Load avatar configuration
   */
  async loadAvatarConfig() {
    try {
      let avatarConfig
      
      if (this.data.isEditing) {
        // Editing mode: load existing configuration
        const result = await avatarUtils.storage.loadAvatarConfig()
        if (result.success) {
          avatarConfig = result.config.toJSON()
        } else {
          avatarConfig = DEFAULT_AVATAR_CONFIG
        }
      } else {
        // Creation mode: use default configuration
        avatarConfig = DEFAULT_AVATAR_CONFIG
      }
      
      this.setData({
        currentAvatarConfig: avatarConfig,
        originalAvatarConfig: JSON.parse(JSON.stringify(avatarConfig))
      })
      
    } catch (error) {
      console.error('Failed to load avatar config:', error)
      // Use default config as fallback
      this.setData({
        currentAvatarConfig: DEFAULT_AVATAR_CONFIG,
        originalAvatarConfig: JSON.parse(JSON.stringify(DEFAULT_AVATAR_CONFIG))
      })
    }
  },

  /**
   * Update dependent data based on current configuration
   */
  updateDependentData() {
    const { currentAvatarConfig } = this.data
    
    // Update clothing options
    this.updateClothingOptions(currentAvatarConfig.clothing.category)
    
    // Update filtered hairstyles
    this.filterHairstyles()
  },

  /**
   * Update clothing options based on category
   */
  updateClothingOptions(category) {
    const categoryKey = category.toUpperCase()
    const clothingItems = AVATAR_OPTIONS.CLOTHING[categoryKey] || []
    
    // Get color options for current item
    const currentItem = clothingItems.find(item => 
      item.id === this.data.currentAvatarConfig.clothing.item
    )
    const clothingColors = currentItem ? currentItem.colors : []
    
    this.setData({
      currentClothingItems: clothingItems,
      currentClothingColors: clothingColors
    })
  },

  /**
   * Filter hairstyles based on gender filter
   */
  filterHairstyles() {
    const { hairstyleOptions, genderFilter } = this.data
    
    let filteredHairstyles = hairstyleOptions
    
    if (genderFilter !== 'all') {
      filteredHairstyles = hairstyleOptions.filter(style => 
        style.gender === 'all' || style.gender === genderFilter
      )
    }
    
    this.setData({ filteredHairstyles })
  },

  /**
   * Handle gender filter change
   */
  onGenderFilterChange(e) {
    const genderFilter = e.detail.value
    this.setData({ genderFilter })
    this.filterHairstyles()
  },

  /**
   * Select face shape
   */
  selectFaceShape(e) {
    const faceShape = e.currentTarget.dataset.value
    this.updateAvatarConfig('faceShape', faceShape)
  },

  /**
   * Select hairstyle
   */
  selectHairstyle(e) {
    const hairstyle = e.currentTarget.dataset.value
    this.updateAvatarConfig('hairstyle', hairstyle)
  },

  /**
   * Select hair color
   */
  selectHairColor(e) {
    const hairColor = e.currentTarget.dataset.value
    this.updateAvatarConfig('hairColor', hairColor)
  },

  /**
   * Select eye shape
   */
  selectEyeShape(e) {
    const eyeShape = e.currentTarget.dataset.value
    this.updateAvatarConfig('eyeShape', eyeShape)
  },

  /**
   * Select clothing category
   */
  selectClothingCategory(e) {
    const category = e.currentTarget.dataset.value
    
    // Update category and reset item and color to defaults
    const categoryItems = AVATAR_OPTIONS.CLOTHING[category.toUpperCase()] || []
    const defaultItem = categoryItems[0]
    const defaultColor = defaultItem ? defaultItem.colors[0] : 'white'
    
    const newClothing = {
      category,
      item: defaultItem ? defaultItem.id : 'tshirt',
      color: defaultColor
    }
    
    this.updateAvatarConfig('clothing', newClothing)
    this.updateClothingOptions(category)
  },

  /**
   * Select clothing item
   */
  selectClothingItem(e) {
    const item = e.currentTarget.dataset.value
    
    // Find the item to get its available colors
    const { currentClothingItems } = this.data
    const clothingItem = currentClothingItems.find(clothingItem => clothingItem.id === item)
    const defaultColor = clothingItem ? clothingItem.colors[0] : 'white'
    
    const newClothing = {
      ...this.data.currentAvatarConfig.clothing,
      item,
      color: defaultColor
    }
    
    this.updateAvatarConfig('clothing', newClothing)
    this.setData({
      currentClothingColors: clothingItem ? clothingItem.colors : []
    })
  },

  /**
   * Select clothing color
   */
  selectClothingColor(e) {
    const color = e.currentTarget.dataset.value
    
    const newClothing = {
      ...this.data.currentAvatarConfig.clothing,
      color
    }
    
    this.updateAvatarConfig('clothing', newClothing)
  },

  /**
   * Select accessory
   */
  selectAccessory(e) {
    const type = e.currentTarget.dataset.type
    const value = e.currentTarget.dataset.value
    
    const newAccessories = {
      ...this.data.currentAvatarConfig.accessories,
      [type]: value
    }
    
    this.updateAvatarConfig('accessories', newAccessories)
  },

  /**
   * Update avatar configuration
   */
  updateAvatarConfig(property, value) {
    const newConfig = {
      ...this.data.currentAvatarConfig,
      [property]: value
    }
    
    this.setData({
      currentAvatarConfig: newConfig
    })
  },

  /**
   * Generate random avatar
   */
  generateRandomAvatar() {
    const { genderFilter } = this.data
    const gender = genderFilter === 'all' ? ['male', 'female'][Math.floor(Math.random() * 2)] : genderFilter
    
    try {
      const randomConfig = AvatarConfig.generateRandom(gender)
      
      this.setData({
        currentAvatarConfig: randomConfig.toJSON()
      })
      
      // Update dependent data for new config
      this.updateDependentData()
      
      showToast('随机头像已生成')
    } catch (error) {
      console.error('Failed to generate random avatar:', error)
      showError('生成随机头像失败')
    }
  },

  /**
   * Save avatar configuration
   */
  async saveAvatar() {
    this.setData({ saving: true })
    
    try {
      // Validate configuration
      const avatarConfig = new AvatarConfig(this.data.currentAvatarConfig)
      const validation = avatarConfig.validate()
      
      if (!validation.isValid) {
        showError('头像配置无效：' + validation.errors.join(', '))
        return
      }
      
      // Save to local storage
      const saveResult = await avatarUtils.storage.saveAvatarConfig(avatarConfig)
      if (!saveResult.success) {
        throw new Error(saveResult.error)
      }
      
      // Save to server
      const serializedConfig = avatarUtils.serializer.serializeForAPI(avatarConfig)
      await post('/api/user/avatar', serializedConfig)
      
      // Update global user profile
      const app = getApp()
      const userProfile = app.getUserProfile() || {}
      userProfile.avatarConfig = avatarConfig.toJSON()
      app.updateUserProfile(userProfile)
      
      showSuccess(this.data.isEditing ? '头像已更新' : '头像创建完成')
      
      // Navigate based on mode
      if (this.data.isEditing) {
        // Return to previous page
        wx.navigateBack()
      } else {
        // New user: navigate to profile or discovery page
        setTimeout(() => {
          navigateTo('/pages/profile/profile')
        }, 1500)
      }
      
    } catch (error) {
      console.error('Failed to save avatar:', error)
      showError('保存头像失败，请重试')
    } finally {
      this.setData({ saving: false })
    }
  },

  /**
   * Cancel editing
   */
  cancelEdit() {
    const hasChanges = JSON.stringify(this.data.currentAvatarConfig) !== 
                     JSON.stringify(this.data.originalAvatarConfig)
    
    if (hasChanges) {
      wx.showModal({
        title: '确认取消',
        content: '你有未保存的修改，确定要取消吗？',
        success: (res) => {
          if (res.confirm) {
            if (this.data.isEditing) {
              wx.navigateBack()
            } else {
              // New user must create avatar
              showToast('请完成头像创建')
            }
          }
        }
      })
    } else {
      if (this.data.isEditing) {
        wx.navigateBack()
      } else {
        showToast('请完成头像创建')
      }
    }
  },

  /**
   * Page unload handler
   */
  onUnload() {
    // Clear any temporary data if needed
  },

  /**
   * 过滤发型选项
   */
  filterHairstyles() {
    const { genderFilter, hairstyleOptions } = this.data;
    
    let filteredHairstyles;
    if (genderFilter === 'all') {
      filteredHairstyles = hairstyleOptions;
    } else {
      filteredHairstyles = hairstyleOptions.filter(style => 
        style.gender === 'all' || style.gender === genderFilter
      );
    }
    
    this.setData({ filteredHairstyles });
  },

  /**
   * 性别过滤器变化
   */
  onGenderFilterChange(event) {
    this.setData({
      genderFilter: event.detail
    });
    this.filterHairstyles();
  },

  /**
   * 选择脸型
   */
  selectFaceShape(event) {
    const faceShape = event.currentTarget.dataset.value;
    this.updateAvatarProperty('faceShape', faceShape);
  },

  /**
   * 选择发型
   */
  selectHairstyle(event) {
    const hairstyle = event.currentTarget.dataset.value;
    this.updateAvatarProperty('hairstyle', hairstyle);
  },

  /**
   * 选择发色
   */
  selectHairColor(event) {
    const hairColor = event.currentTarget.dataset.value;
    this.updateAvatarProperty('hairColor', hairColor);
  },

  /**
   * 选择眼型
   */
  selectEyeShape(event) {
    const eyeShape = event.currentTarget.dataset.value;
    this.updateAvatarProperty('eyeShape', eyeShape);
  },

  /**
   * 选择服装类别
   */
  selectClothingCategory(event) {
    const category = event.currentTarget.dataset.value;
    
    // 更新服装类别，并重置为该类别的第一个项目
    const categoryKey = category.toUpperCase();
    const clothingItems = AVATAR_OPTIONS.CLOTHING[categoryKey] || [];
    
    if (clothingItems.length > 0) {
      const firstItem = clothingItems[0];
      const newClothing = {
        category: category,
        item: firstItem.id,
        color: firstItem.colors[0]
      };
      
      this.updateAvatarProperty('clothing', newClothing);
      this.updateClothingOptions(category);
    }
  },

  /**
   * 选择服装款式
   */
  selectClothingItem(event) {
    const item = event.currentTarget.dataset.value;
    const { currentAvatarConfig } = this.data;
    
    // 找到选中项目的颜色选项
    const categoryKey = currentAvatarConfig.clothing.category.toUpperCase();
    const clothingItems = AVATAR_OPTIONS.CLOTHING[categoryKey] || [];
    const selectedItem = clothingItems.find(clothingItem => clothingItem.id === item);
    
    if (selectedItem) {
      const newClothing = {
        ...currentAvatarConfig.clothing,
        item: item,
        color: selectedItem.colors[0] // 重置为第一个可用颜色
      };
      
      this.updateAvatarProperty('clothing', newClothing);
      this.setData({
        currentClothingColors: selectedItem.colors
      });
    }
  },

  /**
   * 选择服装颜色
   */
  selectClothingColor(event) {
    const color = event.currentTarget.dataset.value;
    const { currentAvatarConfig } = this.data;
    
    const newClothing = {
      ...currentAvatarConfig.clothing,
      color: color
    };
    
    this.updateAvatarProperty('clothing', newClothing);
  },

  /**
   * 选择配饰
   */
  selectAccessory(event) {
    const type = event.currentTarget.dataset.type;
    const value = event.currentTarget.dataset.value;
    const { currentAvatarConfig } = this.data;
    
    const newAccessories = {
      ...currentAvatarConfig.accessories,
      [type]: value
    };
    
    this.updateAvatarProperty('accessories', newAccessories);
  },

  /**
   * 更新头像属性
   */
  updateAvatarProperty(property, value) {
    const { currentAvatarConfig } = this.data;
    const newConfig = { ...currentAvatarConfig };
    
    if (property.includes('.')) {
      // 处理嵌套属性
      const [parent, child] = property.split('.');
      newConfig[parent] = { ...newConfig[parent], [child]: value };
    } else {
      newConfig[property] = value;
    }
    
    // 验证配置
    const avatarInstance = new AvatarConfig(newConfig);
    const validation = avatarInstance.validate();
    
    if (validation.isValid) {
      this.setData({
        currentAvatarConfig: newConfig
      });
    } else {
      console.warn('Invalid avatar configuration:', validation.errors);
      Toast.fail('配置无效，请重试');
    }
  },

  /**
   * 生成随机头像
   */
  generateRandomAvatar() {
    try {
      const randomConfig = AvatarConfig.generateRandom(this.data.genderFilter);
      
      this.setData({
        currentAvatarConfig: randomConfig.toJSON()
      });
      
      // 更新依赖数据
      this.updateDependentData();
      
      Toast.success('随机生成完成');
    } catch (error) {
      console.error('Failed to generate random avatar:', error);
      Toast.fail('生成失败，请重试');
    }
  },

  /**
   * 保存头像
   */
  async saveAvatar() {
    this.setData({ saving: true });
    
    try {
      // 验证配置
      const avatarInstance = new AvatarConfig(this.data.currentAvatarConfig);
      const validation = avatarInstance.validate();
      
      if (!validation.isValid) {
        Toast.fail('头像配置无效，请检查设置');
        return;
      }
      
      // 保存到本地存储
      const saveResult = await avatarUtils.storage.saveAvatarConfig(avatarInstance);
      
      if (saveResult.success) {
        Toast.success(this.data.isEditing ? '头像已更新' : '头像创建成功');
        
        // 延迟跳转，让用户看到成功提示
        setTimeout(() => {
          this.navigateBack();
        }, 1500);
      } else {
        Toast.fail('保存失败：' + saveResult.error);
      }
      
    } catch (error) {
      console.error('Failed to save avatar:', error);
      Toast.fail('保存失败，请重试');
    } finally {
      this.setData({ saving: false });
    }
  },

  /**
   * 取消编辑
   */
  cancelEdit() {
    // 检查是否有未保存的更改
    const hasChanges = JSON.stringify(this.data.currentAvatarConfig) !== 
                      JSON.stringify(this.data.originalAvatarConfig);
    
    if (hasChanges) {
      Dialog.confirm({
        title: '确认取消',
        message: '您有未保存的更改，确定要取消吗？',
        confirmButtonText: '确定取消',
        cancelButtonText: '继续编辑'
      }).then(() => {
        this.navigateBack();
      }).catch(() => {
        // 用户选择继续编辑，不做任何操作
      });
    } else {
      this.navigateBack();
    }
  },

  /**
   * 返回上一页
   */
  navigateBack() {
    if (getCurrentPages().length > 1) {
      wx.navigateBack();
    } else {
      // 如果没有上一页，跳转到首页
      wx.switchTab({
        url: '/pages/discovery/discovery'
      });
    }
  },

  /**
   * 页面分享
   */
  onShareAppMessage() {
    return {
      title: '青鸟笺 - 创建专属虚拟头像',
      path: '/pages/avatar/avatar',
      imageUrl: '/images/share-avatar.png'
    };
  },

  /**
   * 页面分享到朋友圈
   */
  onShareTimeline() {
    return {
      title: '青鸟笺 - 创建专属虚拟头像',
      imageUrl: '/images/share-avatar.png'
    };
  }
})